package com.zdb.java.thread;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

class MyData {
    volatile int number = 0;

    public void addTo60() {
        this.number = 60;
    }

    public int getNumber() {
        return this.number;
    }

    public void addPlusPlus() {
        this.number ++;
    }

    AtomicInteger atomicInteger = new AtomicInteger();

    public void atomAdd() {
        this.atomicInteger.getAndIncrement();
    }
}


public class VolatileDemo {

    public static void main(String[] args) throws Exception {

//        testVisibility();
        testAtom();

    }

    /**
     * 测试 volatile 原子性
     */
    public static void testAtom() {
        MyData myData = new MyData();

        for (int i = 0; i < 2; i++) {
            new Thread(() -> {
                for (int j = 0; j < 1000; j++) {
                    myData.addPlusPlus();
                    myData.atomAdd();
                }

            }, "t_" + i).start();
        }

        while(Thread.activeCount() > 2) {
            Thread.yield();
        }
        System.out.println(Thread.currentThread().getName() + "\t int type: " + myData.getNumber());
        System.out.println(Thread.currentThread().getName() + "\t AtomicInteger: " + myData.atomicInteger);
    }


    public static void testVisibility() {
        MyData myData = new MyData();
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + "\t come in");

            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (Exception e) {
                e.printStackTrace();
            }

            myData.addTo60();

            System.out.println(Thread.currentThread().getName() + "\t updated number");



        }, "AA").start();

//        while(myData.number == 0) {
//        }
        while(myData.number == 0) {
//            System.out.println(myData.number);
            System.out.println("---------");
        }
//        while(myData.getNumber() == 0) {
//            System.out.println(myData.getNumber());
////            TimeUnit.SECONDS.sleep(1);
//        }

        System.out.println(Thread.currentThread().getName() + "\t mission is over");
    }




}
